package cn.mrlong.base.ktnet.adapter

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type


/**
 * 作者：BINGO
 * 时间：2021/04/25 17:34
 */
class MGsonConverterFactory<T> private constructor(
    private val gson: Gson,
    private val baseClazz: Class<T>
) : Converter.Factory() {
    override fun responseBodyConverter(
        type: Type, annotations: Array<Annotation>, retrofit: Retrofit
    ): Converter<ResponseBody, T> {
        val adapter = gson.getAdapter(TypeToken.get(type)) as TypeAdapter<T>
        return MGsonResponseBodyConverter<T>(gson, adapter, baseClazz)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<Annotation>,
        methodAnnotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody> {
        val adapter = gson.getAdapter(TypeToken.get(type)) as TypeAdapter<T>
        return MGsonRequestBodyConverter<T>(gson, adapter)
    }


    companion object {
        fun <T> create(baseClazz: Class<T>?): MGsonConverterFactory<T> {
            return create(Gson(), baseClazz)
        }

        fun <T> create(gson: Gson?, baseClazz: Class<T>?): MGsonConverterFactory<T> {
            if (gson == null) throw NullPointerException("gson == null")
            if (baseClazz == null) throw NullPointerException("baseClazz == null")
            return MGsonConverterFactory(gson, baseClazz)
        }
    }
}